package gmodel

import (
	"context"
	"fmt"
	"gitee.com/851537/gmodel/rds"
	"github.com/google/uuid"
	"github.com/nsqio/go-nsq"
	"github.com/redis/go-redis/v9"
	"reflect"
	"time"
)

// 线程器,独立基类,供实体类继承使用
// used for nsq topic
type BaseRedisThread struct {
	ThreadId string `json:"thread_id"` //gen by snowflake
}

//param:child must prt type
func (this *BaseRedisThread) redisThreadName(child nsq.Handler, key string) string {
	return fmt.Sprintf("union_thread.%s.%s", reflect.ValueOf(child).Elem().Type().Name(), key)
}

func (this *BaseRedisThread) getCmd(child nsq.Handler, key string) *redis.StringCmd {
	return rds.ClientIns().Get(context.Background(), this.redisThreadName(child, key))
}

func (this *BaseRedisThread) GetThread(child nsq.Handler, key string) string {
	return this.getCmd(child, key).Val() //String()
}

func (this *BaseRedisThread) SetThread(child nsq.Handler, key string, expireTime ...int64) error {
	var (
		expire int64
		err    error
	)
	if len(expireTime) > 0 {
		expire = expireTime[0]
	} else {
		expire = 90 * 24 * 3600 //default 90 days expire
	}
	this.ThreadId = uuid.New().String()
	_, err = rds.ClientIns().Set(context.Background(), this.redisThreadName(child, key), this.ThreadId, time.Duration(expire)*time.Second).Result()
	return err
}

func (this *BaseRedisThread) DelThread(child nsq.Handler, key string) (err error) {
	_, err = rds.ClientIns().Del(context.Background(), this.redisThreadName(child, key)).Result()
	return err
}
